package com.ruoyi.cms.service.impl;

import com.aliyun.green20220302.Client;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.ruoyi.api.feign.ContentModerationService;
import com.ruoyi.cms.entity.domain.UserMediaFile;
import com.ruoyi.cms.entity.req.UserMediaListReq;
import com.ruoyi.cms.service.ContentModerationJobService;
import com.ruoyi.common.context.AppUserContext;
import com.ruoyi.common.core.domain.R;
import com.ruoyi.common.enums.cms.FileModerationStatusEnum;
import com.ruoyi.common.enums.cms.OriginalFileType;
import com.ruoyi.common.exception.modules.CmsException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import com.ruoyi.cms.mapper.UserMediaFileMapper;
import com.ruoyi.cms.service.UserMediaFileService;
import lombok.extern.slf4j.Slf4j;

import java.util.Date;
import java.util.List;

/**
 * 用户媒体Service业务层处理
 */
@Service
@Slf4j
public class UserMediaFileServiceImpl implements UserMediaFileService {

    @Autowired
    private UserMediaFileMapper userMediaFileMapper;
    @Autowired
    private ContentModerationJobService contentModerationJobService;
    @Autowired
    private ContentModerationService contentModerationService;

    @Value("${ruoyi.env}")
    private String env;

    @Override
    public R<Page<UserMediaFile>> list(UserMediaListReq req) {
        Long userId = AppUserContext.getUser().getUserId();
        Page<UserMediaFile> page = new Page<>(req.getCurrent(), req.getSize());

        LambdaQueryWrapper<UserMediaFile> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(UserMediaFile::getType, req.getType());
        queryWrapper.eq(UserMediaFile::getCreator, userId);
        queryWrapper.orderByDesc(UserMediaFile::getId);
        page = userMediaFileMapper.selectPage(page, queryWrapper);

        return R.ok(page);
    }

    @Override
    public R<?> add(List<UserMediaFile> list) {
        boolean isTest = env.contains("test");
        Long userId = AppUserContext.getUser().getUserId();
        Date now = new Date();
        list.forEach(e -> {
            if (OriginalFileType.VIDEO.getType().equals(e.getType())) {
                e.setCoverPhotoUrl(e.getUrl() + "?x-oss-process=video/snapshot,t_1,f_jpg,ar_auto");
            }

            e.setCreator(userId);
            e.setCreateTime(now);

            if(isTest){
                e.setModerationStatus(FileModerationStatusEnum.PASS.getStatus());
            }

            userMediaFileMapper.insert(e);
        });


        if (!isTest) {
            new Thread(() -> {
                Client client;
                try {
                    client = contentModerationService.createSHClient();
                } catch (Exception e) {
                    log.error("内容审核失败", e);
                    throw new CmsException("内容审核失败");
                }
                list.forEach(userMediaFile -> {
                    try {
                        contentModerationJobService.mediaModeration(userMediaFile, client);
                    } catch (Exception e) {
                        log.error("内容审核失败, id: " + userMediaFile.getId(), e);
                    }
                });
            }).start();
        }


        return R.ok();
    }

    @Override
    public R<?> delete(List<String> ids) {
        Long userId = AppUserContext.getUser().getUserId();
        ids.forEach(id -> {
            UserMediaFile userMediaFile = userMediaFileMapper.selectById(id);
            if (null == userMediaFile) {
                throw new CmsException("文件不存在");
            }
            if (!userMediaFile.getCreator().equals(userId)) {
                throw new CmsException("无权限删除");
            }
            userMediaFileMapper.deleteById(id);
        });
        return R.ok();
    }

}
